package cate.game.gm.sub;

import cate.game.GameBody;
import cate.game.rank.h.RankHandler;
import cate.game.rank.po.Rank;
import cate.game.rank.vo.RankParam;
import cate.game.role.Role;
import cate.game.role.base.msg.RoleBaseInitResp;
import cp.solution.business.gm.cmd.GmTempCmd;
import easy.java.practice.errorcode.EcException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.List;

@Slf4j
public class GmRoleRenameRun {

    public static String run(GameBody game, GmTempCmd cmd) {
        Role role = game.role.getRole(cmd.roleId);
        if(role == null) {
            throw new EcException("找不到角色ID="+cmd.roleId+"的玩家").s();
        }
        String oldName = role.getBase().name;
        role.getBase().name = cmd.roleName();
        new RoleBaseInitResp().data(role.getBase()).sendNow(role);

        if(role.getRes().guild.checkGuild().ok()) {
            role.getRes().guild.getGuild().member.list.forEach(m -> {
                if(StringUtils.equals(m.it.uid, cmd.roleId())) {
                    m.it.base.name = cmd.roleName();
                }
            });
        }
        RankParam rp = new RankParam();
        rp.executor = role;

        hRank(game.rank.tower, cmd);
        game.rank.camps.getHandlers().forEach(h -> hRankList(h.getRankList(rp), cmd));
        hRank(game.rank.achievements, cmd);
        hRank(game.rank.power, cmd);
        hRank(game.rank.level, cmd);
        game.rank.forbidden.getHandlers().forEach(h -> hRankList(h.getRankList(rp), cmd));
        hRank(game.rank.endless, cmd);
        new Thread(() -> {
            try {
                game.rank.getPointRaceAdapter().getRankList(rp).forEach(item -> hRankItem(item, cmd));
                game.rank.getEliteRaceAdapter().getRankList(rp).forEach(item -> hRankItem(item, cmd));
                game.rank.championRace.getRankList(rp).forEach(h -> hRankItem(h, cmd));
                game.rank.teamPvp.getRankList(rp).forEach(h -> hRankItem(h, cmd));
            } catch (Exception e) {
                log.error("", e);
            }
        }).start();
        hRank(game.rank.udgPalace, cmd);
        return "已将玩家("+oldName+") 改名为 "+role.getBase().name;
    }

    private static void hRank(RankHandler rankHandler, GmTempCmd cmd) {
        Rank rank = rankHandler.getByUid(cmd.roleId());
        hRankItem(rank, cmd);
    }

    private static void hRankList(List<? extends Rank> rankList, GmTempCmd cmd) {
        if(rankList != null) {
            for(Rank rank : rankList) {
                hRankItem(rank, cmd);
            }
        }
    }

    private static void hRankItem(Rank rank, GmTempCmd cmd) {
        if(rank != null) {
            rank.owner.base.name = cmd.roleName();
        }
    }
}
